#include "managewidget.h"


ManageWidget::ManageWidget(QWidget *parent) : QWidget(parent)
{
    label = new QLabel("品牌车管理");
    label->setMinimumHeight(20);
    label->setFrameStyle(QLabel::StyledPanel);
    label->setAlignment(Qt::AlignCenter);
    widget = new QWidget;
    listWidget = new QListWidget;
    QHBoxLayout* bottomLayout = new QHBoxLayout;
    bottomLayout->addWidget(widget);
    bottomLayout->addWidget(listWidget);
    QHBoxLayout* topLayout = new QHBoxLayout;
    topLayout->addWidget(label);
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->addSpacing(20);
    mainLayout->addLayout(topLayout);
    mainLayout->addLayout(bottomLayout);


    topLabel = new QLabel("出售车辆");
    topLabel->setMaximumHeight(20);
    topLabel->setFrameStyle(QLabel::StyledPanel);
    sellFactoryLabel = new QLabel("厂家：");
    sellFactoryComboBox = new QComboBox;
    sellBrandLabel = new QLabel("品牌：");
    sellBrandComboBox = new QComboBox;
    sellPriceLabel = new QLabel("报价：");
    sellPriceLineEdit = new QLineEdit;
    sellPriceUnitLabel = new QLabel("万");
    sellNumberLabel = new QLabel("数量：");
    sellNumberSpinBox = new QSpinBox;
    sellLastNumberLabel = new QLabel("剩余数量：000");
    sellSumLabel = new QLabel("金额：");
    sellSumLineEdit = new QLineEdit;
    sellSumUnitLabel = new QLabel("万");
    okButton = new QPushButton("确定");
    okButton->setEnabled(false);
    cancelButton = new QPushButton("取消");
    bottomLabel = new QLabel("已有新车入库");
    bottomLabel->setMaximumHeight(20);
    bottomLabel->setFrameStyle(QLabel::StyledPanel);
    QGridLayout* leftLayout = new QGridLayout(widget);
    leftLayout->addWidget(topLabel, 0, 0, 1, 4);
    leftLayout->addWidget(sellFactoryLabel, 1, 0);
    leftLayout->addWidget(sellFactoryComboBox, 1, 1);
    leftLayout->addWidget(sellBrandLabel, 2, 0);
    leftLayout->addWidget(sellBrandComboBox, 2, 1);
    leftLayout->addWidget(sellPriceLabel, 3, 0);
    leftLayout->addWidget(sellPriceLineEdit, 3, 1);
    leftLayout->addWidget(sellPriceUnitLabel, 3, 2);
    leftLayout->addWidget(sellNumberLabel, 4, 0);
    leftLayout->addWidget(sellNumberSpinBox, 4, 1);
    leftLayout->addWidget(sellLastNumberLabel, 4, 2);
    leftLayout->addWidget(sellSumLabel, 5, 0);
    leftLayout->addWidget(sellSumLineEdit, 5, 1);
    leftLayout->addWidget(sellSumUnitLabel, 5, 2);
    leftLayout->addWidget(okButton, 6, 1);
    leftLayout->addWidget(cancelButton, 6, 3);
    leftLayout->addWidget(bottomLabel, 7, 0, 1, 4);

    QSqlQueryModel* factoryModel = new QSqlQueryModel(this);
    factoryModel->setQuery("select name from factory");    //得到数据
    sellFactoryComboBox->setModel(factoryModel);    //设置到Box

    connect(sellFactoryComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(on_sellFactoryComboBox_currentIndexChanged(QString)));
    connect(sellBrandComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(on_sellBrandComboBox_currentIndexChanged(QString)));
    connect(sellNumberSpinBox, SIGNAL(valueChanged(int)), this, SLOT(on_sellNumberSpinBox_valueChanged(int)));
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(on_cancelButton_clicked()));
    connect(okButton, SIGNAL(clicked()), this, SLOT(on_okButton_clicked()));
    showDailyList();
}

void ManageWidget::on_sellBrandComboBox_currentIndexChanged(const QString &arg1)
{
    sellNumberSpinBox->setValue(0);
    sellNumberSpinBox->setEnabled(false);
    sellSumLineEdit->clear();
    sellSumLineEdit->setEnabled(false);
    okButton->setEnabled(false);

    QSqlQuery query;
    query.exec(QString("select price from brand where name='%1' and factory='%2'").arg(arg1).arg(sellFactoryComboBox->currentText()));
    query.next();
    sellPriceLineEdit->setEnabled(true);
    sellPriceLineEdit->setReadOnly(true);
    sellPriceLineEdit->setText(query.value(0).toString());
    query.exec(QString("select last from brand where name='%1' and factory='%2'").arg(arg1).arg(sellFactoryComboBox->currentText()));
    query.next();
    int number = query.value(0).toInt();
    if(number == 0)
    {
        QMessageBox::information(this, "提示", "该品牌汽车已经售完！", QMessageBox::Ok);
    }
    else
    {
        sellNumberSpinBox->setEnabled(true);
        sellNumberSpinBox->setMaximum(number);
        sellLastNumberLabel->setText(tr("剩余数量：%1").arg(number));
        sellLastNumberLabel->setVisible(true);
    }
}

void ManageWidget::on_sellFactoryComboBox_currentIndexChanged(const QString &arg1)
{
    if(arg1 == "请选择厂家")
    {
        on_cancelButton_clicked();
    }
    else
    {
        sellBrandComboBox->setEnabled(true);
        QSqlQueryModel* model = new QSqlQueryModel(this);
        model->setQuery(QString("select name from brand where factory='%1'").arg(arg1));
        sellBrandComboBox->setModel(model);
        cancelButton->setEnabled(true);
    }
}

void ManageWidget::on_sellNumberSpinBox_valueChanged(int count)
{
    if(count == 0)
    {
        sellSumLineEdit->clear();
        sellSumLineEdit->setEnabled(false);
        okButton->setEnabled(false);
    }
    else
    {
        sellSumLineEdit->setEnabled(true);
        sellSumLineEdit->setReadOnly(true);
        qreal sum = count * sellPriceLineEdit->text().toInt();   //数量乘以单价得总价
        sellSumLineEdit->setText(QString::number(sum));
        okButton->setEnabled(true);
    }
}

void ManageWidget::on_cancelButton_clicked()
{
    sellFactoryComboBox->setCurrentIndex(0);
    sellBrandComboBox->clear();    //这个不起作用
    sellPriceLineEdit->clear();
    sellSumLineEdit->clear();
    sellLastNumberLabel->setText("剩余数量：000");
    sellNumberSpinBox->clear();
    okButton->setEnabled(false);
}

void ManageWidget::on_okButton_clicked()
{
    VerifyDialog* dialog = new VerifyDialog(this);
    if(dialog->exec() == QDialog::Accepted)
    {
        username = dialog->usernameLineEdit->text();
        QString factory = sellFactoryComboBox->currentText();
        QString name = sellBrandComboBox->currentText();
        int value = sellNumberSpinBox->value();
        int last = sellNumberSpinBox->maximum() - value;   //剩余数量
        QSqlQuery query;
        query.exec(QString("select sell from brand where name='%1' and factory='%2'").arg(name).arg(factory));
        query.next();
        int sell = query.value(0).toInt() + value;    //售出数量

        QSqlDatabase::database().transaction();
        bool success = query.exec(QString("update brand set sell=%1, last=%2 where name='%3' and factory='%4'").arg(sell).arg(last).arg(name).arg(factory));
        if(success)
        {
            QSqlDatabase::database().commit();
            QMessageBox::information(this, "提示", "购车成功", QMessageBox::Ok);
            writeXml();
            showDailyList();
            on_cancelButton_clicked();
        }
        else
        {
            QSqlDatabase::database().rollback();
        }
    }
    else
    {
        QMessageBox::information(this, "提示", "购车失败", QMessageBox::Ok);
    }
}

QString ManageWidget::getDateTime(DateTimeType type)
{
    QDateTime datetime = QDateTime::currentDateTime();
    QString date = datetime.toString("yyyy-MM-dd");
    QString time = datetime.toString("hh:mm");
    QString dateAndTime = datetime.toString("yyyy-MM-dd dddd hh:mm");
    if(type == Date)
    {
        return date;
    }
    else if(type == Time)
    {
        return time;
    }
    else
    {
        return dateAndTime;
    }
}

bool ManageWidget::docRead()    //把data.xml内容读取到doc中
{
    QFile file("data.xml");
    if(!file.open(QIODevice::ReadOnly))
    {
        return false;
    }
    if(!doc.setContent(&file))
    {
        file.close();
        return false;
    }
    file.close();
    return true;
}

bool ManageWidget::docWrite()
{
    QFile file("data.xml");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        return false;
    }
    QTextStream out(&file);
    doc.save(out, 4);
    file.close();
    return true;
}

void ManageWidget::writeXml()
{
   if(docRead())
   {
       QString currentDate = getDateTime(Date);
       QDomElement root = doc.documentElement();
       if(!root.hasChildNodes())
       {
           QDomElement date = doc.createElement(QString("日期"));
           QDomAttr curDate = doc.createAttribute("date");
           curDate.setValue(currentDate);
           date.setAttributeNode(curDate);
           root.appendChild(date);
           createNodes(date);
       }
       else
       {
           QDomElement date = root.lastChild().toElement();
           if(date.attribute("date") == currentDate)
           {
               createNodes(date);
           }
           else
           {
               QDomElement date = doc.createElement(QString("日期"));
               QDomAttr curDate = doc.createAttribute("date");
               curDate.setValue(currentDate);
               date.setAttributeNode(curDate);
               root.appendChild(date);
               createNodes(date);
           }

       }
       docWrite();
   }
}

void ManageWidget::createNodes(QDomElement &date)
{
    QDomElement time = doc.createElement(QString("时间"));   //时间  element
    QDomAttr curTime = doc.createAttribute("time");    //time  Attr
    curTime.setNodeValue(getDateTime(Time));    //设置time Attr 的值
    time.setAttributeNode(curTime);    //把time Attr 设置成 时间element 的属性
    date.appendChild(time);    //设置time为 date的子元素
    QDomElement handPerson = doc.createElement(QString("经手人"));
    QDomElement factory = doc.createElement(QString("厂家"));
    QDomElement brand = doc.createElement(QString("品牌"));
    QDomElement price = doc.createElement(QString("报价"));
    QDomElement num = doc.createElement(QString("数量"));
    QDomElement sum = doc.createElement(QString("金额"));
    QDomText text;

    text = doc.createTextNode(username);    //这里记录经手人
    handPerson.appendChild(text);
    text = doc.createTextNode(QString("%1").arg(sellFactoryComboBox->currentText()));
    factory.appendChild(text);
    text = doc.createTextNode(QString("%1").arg(sellBrandComboBox->currentText()));
    brand.appendChild(text);
    text = doc.createTextNode(QString("%1").arg(sellPriceLineEdit->text()));
    price.appendChild(text);
    text = doc.createTextNode(QString("%1").arg(sellNumberSpinBox->value()));
    num.appendChild(text);
    text = doc.createTextNode(QString("%1").arg(sellSumLineEdit->text()));
    sum.appendChild(text);

    time.appendChild(handPerson);
    time.appendChild(factory);
    time.appendChild(brand);
    time.appendChild(price);
    time.appendChild(num);
    time.appendChild(sum);
}

void ManageWidget::showDailyList()
{
    listWidget->clear();
    if(docRead())
    {
        QDomElement root = doc.documentElement();
        QString title = root.tagName();
        QListWidgetItem* titleItem = new QListWidgetItem;
        titleItem->setText(QString("-------%1-------").arg(title));
        titleItem->setTextAlignment(Qt::AlignCenter);
        listWidget->addItem(titleItem);
        if(root.hasChildNodes())
        {
            QString currentDate = getDateTime(Date);
            QDomElement dateElement = root.lastChild().toElement();
            QString date =dateElement.attribute("date");
            if(date == currentDate)   //只显示当天的
            {
                listWidget->addItem("");
                listWidget->addItem(QString("日期：%1").arg(date));
                listWidget->addItem("");
                QDomNodeList children = dateElement.childNodes();
                for(int i = 0; i < children.count(); i++)
                {
                    QDomNode node = children.at(i);
                    QString time = node.toElement().attribute("time");
                    QDomNodeList list = node.childNodes();
                    QString handPerson = list.at(0).toElement().text();
                    QString factory = list.at(1).toElement().text();
                    QString brand = list.at(2).toElement().text();
                    QString price = list.at(3).toElement().text();
                    QString num = list.at(4).toElement().text();
                    QString sum = list.at(5).toElement().text();
                    QString str = "时间：" + time + "\n" + "经手人：" + handPerson + "\n品牌：" + brand + "  " + factory + "\n"
                            + "数量："  + num + " 辆\n" + "成交价：" + price + " 万元\n" + "共计：" + sum + " 万元";
                    QListWidgetItem* tempItem = new QListWidgetItem;
                    tempItem->setText("*********************************");
                    tempItem->setTextAlignment(Qt::AlignCenter);
                    listWidget->addItem(tempItem);
                    listWidget->addItem(str);
                }
            }
        }
    }
}

VerifyDialog::VerifyDialog(QWidget *parent) : QDialog(parent)
{
    setFixedSize(400, 300);
    setWindowTitle("身份验证");
    welcomeLabel = new QLabel("请验证身份！");
    welcomeLabel->setFixedHeight(40);
    welcomeLabel->setFrameStyle(QLabel::StyledPanel);
    welcomeLabel->setAlignment(Qt::AlignCenter);
    usernameLabel = new QLabel("用户名：");
    usernameLineEdit = new QLineEdit;
    passwordLabel = new QLabel("密码");
    passwordLineEdit = new QLineEdit;
    passwordLineEdit->setEchoMode(QLineEdit::Password);    //小黑点
    okButton = new QPushButton("验证");
    cancelButton = new QPushButton("取消");
    QGridLayout* mainLayout = new QGridLayout(this);
    mainLayout->addWidget(welcomeLabel, 1, 0, 1, 7);
    mainLayout->addWidget(usernameLabel, 2, 1, 1, 1);
    mainLayout->addWidget(usernameLineEdit, 2, 2, 1, 3);
    mainLayout->addWidget(passwordLabel, 3, 1, 1, 1);
    mainLayout->addWidget(passwordLineEdit, 3, 2, 1, 3);
    mainLayout->addWidget(okButton, 4, 2, 1, 1);
    mainLayout->addWidget(cancelButton, 4, 4, 1, 1);
    connect(okButton, SIGNAL(clicked(bool)), this, SLOT(slotOkButton()));
    connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(slotcancelButton()));
}

void VerifyDialog::slotcancelButton()
{
    QDialog::reject();
}

void VerifyDialog::slotOkButton()
{
    if(usernameLineEdit->text().isEmpty())
    {
        QMessageBox::information(this, "提示", "请输入用户名！", QMessageBox::Ok);
    }
    else
    {
        if(passwordLineEdit->text().isEmpty())
        {
            QMessageBox::information(this, "提示", "请输入密码！", QMessageBox::Ok);
        }
        else
        {
            QString username = usernameLineEdit->text();
            QString password = passwordLineEdit->text();
            QSqlQuery query;
            query.exec(QString("select password from passwordtable where username='%1'").arg(username));
            query.next();
            if(query.value(0).toString() == password)
            {
                QDialog::accept();
            }
            else
            {
                QMessageBox::warning(this, "密码错误！", "请输入正确密码！", QMessageBox::Ok);
                passwordLineEdit->clear();
                passwordLineEdit->setFocus();
            }
        }
    }
}
